package com.biostime.qdingding.modules.qd.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.biostime.qdingding.common.api.FastResponse;
import com.biostime.qdingding.common.api.ListResponse;
import com.biostime.qdingding.common.api.ObjResponse;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.cms.service.ArticleService;
import com.biostime.qdingding.modules.qd.api.dto.ArticleDto;
import com.biostime.qdingding.modules.qd.api.dto.CommentDto;
import com.biostime.qdingding.modules.qd.api.dto.CourseDto;
import com.biostime.qdingding.modules.qd.api.dto.CourseOrderDto;
import com.biostime.qdingding.modules.qd.api.dto.CoursesOrderingDto;
import com.biostime.qdingding.modules.qd.api.dto.MessageDto;
import com.biostime.qdingding.modules.qd.entity.Album;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.service.AlbumService;
import com.biostime.qdingding.modules.qd.service.CommentService;
import com.biostime.qdingding.modules.qd.service.CourseService;
import com.biostime.qdingding.modules.qd.service.CoursepriceService;
import com.biostime.qdingding.modules.qd.service.MessageService;
import com.biostime.qdingding.modules.qd.service.PriceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 首页模块
 * 
 * @author chenweicheng
 * @version 2015-12-01
 */
@RestController
@RequestMapping(value = "${adminPath}/qd/api/mainPage")
public class MainPageApi extends BaseController {
	
	
	@Autowired
	private CourseService courseService;


	@Autowired
	private CommentService commentService;

	@Autowired
	private AlbumService albumService;
		
	@Autowired
	private PriceService moneyService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private CoursepriceService priceService;
	
	@Autowired
	private ArticleService articleService;

	/**
	 * 首页/轮播图
	 */
	@RequestMapping(value = "scrollImage")
	public ListResponse<HashMap<String, Object>> scrollImage(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		String centerId = request.getParameter("centerId");
		String studentId = request.getParameter("studentId");
		String categoryId = request.getParameter("categoryId");
		String message = null;
		List<HashMap<String,Object>>  list = new ArrayList<HashMap<String,Object>>();	
		
		if (userId != null && !userId.equals("") && centerId != null && !centerId.equals("")) {
			if(studentId != null && studentId.equals(String.valueOf(BasicApi.defaultStudentId))){ 
				centerId = String.valueOf(BasicApi.defaultCenterId);
			}
			list = albumService.apiGetScollImages(centerId,categoryId);
			
			//项目url
			String projectUrl = request.getRequestURI();
			String url[] = projectUrl.split("/");
			if(url.length>3){
				projectUrl = url[0]+"/"+url[1]+"/"+url[2];
			}
			
			//图片跳转页面
			for(int i = 0;i<list.size();i++){
				 if(list.get(i).get("url").equals("0")){
					 list.get(i).put("url", null);
				 }
				 if(list.get(i).get("linkUrl").equals("0")){
					 list.get(i).put("linkUrl", null);
				 }
				 list.get(i).put("jumpUrl",projectUrl+"/qd/article/show/"+list.get(i).get("id")); 			
			}
			message = "获取轮播图成功";
		} else {
			message = "获取轮播图失败,参数不全";
		}
		
		return  FastResponse.create().errMsg(message).list(list);
		
	}
	
	/**
	 * 获取首页推荐文章列表
	 */
	@RequestMapping(value = "getRecommendArticle")
	public ListResponse<ArticleDto> getArticles(HttpServletRequest request) {	
		String userId = request.getParameter("userId");
		String message = null;
		int errCode = 0;
		List<ArticleDto>  articleList = new ArrayList<ArticleDto>();
		
		if (userId != null && !userId.equals("")) {	
			articleList = articleService.getRecommendArticle(null, null);
			//项目url
			String projectUrl = request.getRequestURI();
			String url[] = projectUrl.split("/");
			if(url.length>3){
				projectUrl = url[0]+"/"+url[1]+"/"+url[2];
			}
			for(ArticleDto dto : articleList){
				dto.setHtmlUrl(projectUrl+"/qd/article/show/"+dto.getId());
			}
			message = "获取推荐文章列表成功";
			errCode = 0;
			
		} else {
			message = "获取推荐文章列表失败，参数有误";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).list(articleList);
	}		
	
	
	/**
	 * 首页/我的消息
	 * 1未读，0已读，2全部
	 */
	@RequestMapping(value = "myMessage")
	public ListResponse<MessageDto> myMessage(HttpServletRequest request) {
		
		//默认显示未读消息,页数为1，条数为10
		String type = "1";
		String pageindex = "1";
		String pagesize = "10";
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");
		type = request.getParameter("type");
		String message = null;
		List<MessageDto> messageList = new ArrayList<MessageDto>();
		List<String> list = null;
		
		if(pageindex != null && !pageindex.equals("") && pagesize != null && !pagesize.equals("")){
			pageindex = request.getParameter("pageindex");
			pagesize= request.getParameter("pagesize");			
		}
		
		if (userId != null && !userId.equals("") && type != null && !type.equals("")) {
			
			//分页操作
			PageHelper.startPage(Integer.parseInt(pageindex), Integer.parseInt(pagesize));
			switch(type){
				case "0" :
					messageList = messageService.apiGetMessages(studentId,type); 
					list = new ArrayList<String>();
					list.add("0");
					for(MessageDto me :messageList){
						list.add(String.valueOf(me.getId()));
					}	
					messageService.apiUpdateState(list);
					break;
				case "1" :
					messageList = messageService.apiGetMessages(studentId,type); 
					break;		
				case "2" :
					messageList = messageService.apiGetMessages(studentId,null); 
					break;
				default:
					messageList = messageService.apiGetMessages(studentId,"1");
				
			}
			message = "获取我的消息成功";
			
		} else {
			message = "获取我的消息失败,参数不全";
		}
		
		return FastResponse.create().errMsg(message).list(messageList);
	}		
	
	/**
	 * 首页/我的消息
	 * 1未读，0已读，2全部
	 */
	@RequestMapping(value = "getMyMessage")
	public ListResponse<MessageDto> getMyMessage(HttpServletRequest request) {
		
		//默认显示未读消息,页数为1，条数为10
		String pageindex = "1";
		String pagesize = "10";
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");
		String message = null;
		List<MessageDto> messageList = new ArrayList<MessageDto>();
		List<String> list = null;
		
		if(pageindex != null && !pageindex.equals("") && pagesize != null && !pagesize.equals("")){
			pageindex = request.getParameter("pageindex");
			pagesize= request.getParameter("pagesize");			
		}
		
		if (userId != null && !userId.equals("") && studentId != null && !studentId.equals("")) {
			
			//分页操作
			PageHelper.startPage(Integer.parseInt(pageindex), Integer.parseInt(pagesize));
			messageList = messageService.apiGetMessages(studentId,null); 
			list = new ArrayList<String>();
			list.add("0");
			for(MessageDto me :messageList){
				if(me.getType().equals("0")) 
				list.add(String.valueOf(me.getId()));
			}	
			messageService.apiUpdateState(list);

			message = "获取我的消息成功";
			
		} else {
			message = "获取我的消息失败,参数不全";
		}
		
		return FastResponse.create().errMsg(message).list(messageList);
	}		
	

	/**
	 * 首页/首页主要内容
	 * 热门课程，我的近期课程，热门活动
	 */
	@RequestMapping(value = "mainPageContent")
	public ObjResponse<HashMap<String, Object>> mainPageContent(HttpServletRequest request) throws Exception{
		
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");
		String centerId = request.getParameter("centerId");
		String message = null;
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		if(userId != null && !userId.equals("") && studentId != null && !userId.equals("") && 
				centerId != null && !centerId.equals("")){
			
			//热门课程
			List<CourseOrderDto> hotCourseList = new ArrayList<CourseOrderDto>();
			if(!studentId.equals(String.valueOf(BasicApi.defaultStudentId))){
				hotCourseList = hotCourses(studentId,centerId);				
			}
		
			//近期课程
			List<CourseDto> courseDtoList = recentCourses(studentId);
			
			//主要活动
			List<HashMap<String,Object>> activityList = new ArrayList<HashMap<String,Object>>();	
			
			//我的消息数量
			int messageNum = 0;
			messageNum = messageService.apiGetMessageCount(studentId);
			
			map.put("hotCourseList", hotCourseList);
			map.put("recentCourseList", courseDtoList);
			map.put("activityList", activityList);
			map.put("messageNum", messageNum);
			
			message = "获取主要内容成功";	
			
		}else{
			message = "获取主要内容失败,参数不全";			
		}
		
		return FastResponse.create().errMsg(message).obj(map);
	}

	/**
	 * 首页/热门课程
	 */
	@RequestMapping(value = "hotCourses")
	public List<CourseOrderDto> hotCourses(String studentId,String centerId) throws Exception{

		double moneyBefore = 0d;
		double moneyAfter = 0d;
		String category = null;
		List<Album> albumList = new ArrayList<Album>();
		List<CourseOrderDto> hotCourseList = null;
		
		//热门课程
		List<CoursesOrderingDto>  dtos = courseService.apiGetHotCourse(studentId,centerId);
		if(dtos != null  && !dtos.isEmpty()){
			hotCourseList = new ArrayList<CourseOrderDto>();
			for(int i=0;i<dtos.size();i++){
				hotCourseList.addAll(dtos.get(i).getCourseOrders());
			}		
		}
		//List<CourseOrderDto> hotCourseList = courseService.apiGetHotCourse(studentId,centerId).getCourseOrders(); 
		if(hotCourseList != null && !hotCourseList.isEmpty()){
			for(int i=0 ;i<hotCourseList.size();i++){
				
				CourseOrderDto courseOrder = hotCourseList.get(i);			
				String type = String.valueOf(courseOrder.getType());
				String courseId = String.valueOf(courseOrder.getId());
							
				//获取统一忙时价格
				double initPrice = 0;
				if(!priceService.apiGetPrice(0, centerId).isEmpty()){
					 initPrice = priceService.apiGetPrice(0, centerId).get(0).getPrice();	
					 initPrice=moneyService.changeMoney(initPrice);
				}
				
				//获取价格类型，优惠前价格，优惠后价格
				int priceType = courseOrder.getPriceType();
				Course course = courseService.apiGetInOrOut(type,courseId);
				HashMap<String,Object> priceMap = moneyService.getPriceMap(course, studentId);
				if(priceMap != null){
					moneyBefore = (double) priceMap.get("moneyBefore");
					moneyAfter = (double) priceMap.get("moneyAfter");			
				}
				
				//设置优惠前价格
				if(priceType ==0 ){
					courseOrder.setMoneyBefore(moneyBefore);
				}else{
					courseOrder.setMoneyBefore(initPrice);
				}
				
				//设置优惠后价格
				courseOrder.setMoneyAfter(moneyAfter); 
				
				//获取课程图片列表
				if (type.equals("0")) {
					category = "course";
				} else {
					category = "outcourse";
				}
				albumList = albumService.apiGet(category, courseId);
				
				//设置课程图片，一张
				if(!albumList.isEmpty()){
					courseOrder.setImage(albumList.get(0).getThumbPath()); 				
				}
	
			}
		}
		
		//待用
/*		//新集合，用于迭代新的课程
		List<CoursesOrderingDto>  courseList = new ArrayList<CoursesOrderingDto>();
		List<CourseOrderDto> hotCourseList2 = null;
		for(int i=0;i<hotCourseList.size();i++){
			CoursesOrderingDto courseDto = new CoursesOrderingDto();
			hotCourseList2 = new ArrayList<CourseOrderDto>();
			hotCourseList2.add(hotCourseList.get(i));
			courseDto.setCourseOrders(hotCourseList2);
			courseList.add(courseDto);
		}
		
		//按价格从低到高重新排序
		courseList=courseService.getCourseByPrice(courseList,"priceup");
		
		//将列表清空，再重新放进排序后的列表
		hotCourseList.clear();
		hotCourseList2 = new ArrayList<CourseOrderDto>();
		for(int i=0;i<courseList.size();i++){
			hotCourseList2.add(courseList.get(i).getCourseOrders().get(0));  
		}
		hotCourseList.addAll(hotCourseList2);*/
		
		return hotCourseList;
	}

	/**
	 * 首页/近期课程
	 */
	@RequestMapping(value = "recentCourses")
	public List<CourseDto> recentCourses(String studentId) {		
		List<CourseDto> courseDtoList = courseService.apiMyRecentCourse(studentId);
		return courseDtoList;
	}
	
	/**
	 * 首页/热门评价
	 */
	@RequestMapping(value = "hotComments")
	public ListResponse<CommentDto> hotComments(HttpServletRequest request) {
		int pageindex = 1;
		int pagesize = 5;
		String message = null;
		String category = null;
		String userId = request.getParameter("userId");
		String centerId = request.getParameter("centerId");
		String studentId = request.getParameter("studentId");
		List<CommentDto> commentList = null;
		List<CommentDto> commentList2 = new ArrayList<CommentDto>();
		CommentDto commentDto = null;
		List<Album> albumList = null;
		String imageUrl = null;
		int errCode = 0;

		if (request.getParameter("pageindex") != null && request.getParameter("pageindex") != null) {
			pageindex = Integer.parseInt(request.getParameter("pageindex"));
			pagesize = Integer.parseInt(request.getParameter("pagesize"));
		}
		
		if (userId != null && !userId.equals("")) {		
			
			if(studentId != null && studentId.equals(BasicApi.defaultStudentId)){
				 centerId = null;
			}
			//分页操作
			PageHelper.startPage(pageindex, pagesize);
			commentList = commentService.apiGetNewComments(centerId,userId);
		
			//将commentList，与之对应的图片放进commentDto内
			for (int i = 0; i < commentList.size(); i++) {
				commentDto = commentList.get(i);
				if (commentDto.getCategory().equals("0")) {
					category = "courseComment";
				} else {
					category = "outcourseComment";
				}
				
				//获取用户评论图片
				albumList = albumService.apiGet(category, String.valueOf(commentDto.getId()));
				
				//获取用户头像
				if(!albumService.apiGet("headImg", String.valueOf(commentDto.getUserId())).isEmpty()){
					imageUrl = albumService.apiGet("headImg", String.valueOf(commentDto.getUserId())).get(0).getThumbPath();
				}
			
				commentDto.setHeadImg((imageUrl)); 
				commentDto.setImages(albumList);
				commentList2.add(commentDto);
			}
			
			message = "查看课程评论列表成功";
			errCode = 0;
		} else {
			message = "查看课程评论列表失败，参数有误";
			errCode = 1;
		}
		
		PageInfo<CommentDto> page = new PageInfo<CommentDto>(commentList);
		
		return FastResponse.create().errCode(errCode).subCode(0).errMsg(message).pageIndex(page.getPageNum())
				.pageSize(page.getPageSize()).total((int) page.getTotal()).hasNext(page.isHasNextPage())
				.list(commentList2);
	}
}
